 
package com.zdkj.subway.rca.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;

import com.zdkj.subway.rca.entity.SwCkClearOtherAccount;

import com.zdkj.subway.rca.mapper.SwCkClearOtherAccountMapper;
import com.zdkj.subway.rca.service.SwCkClearOtherAccountService;
import com.zdkj.subway.rca.service.SwCkSysCleaningConsTicketService;
import com.zdkj.subway.rca.util.MyBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 应急纸票与退款清分表
 *
 * @author stw
 * @date 2021-01-01 18:02:59
 */
@Service
public class SwCkClearOtherAccountServiceImpl extends ServiceImpl<SwCkClearOtherAccountMapper, SwCkClearOtherAccount> implements SwCkClearOtherAccountService {
    @Autowired
    private SwCkSysCleaningConsTicketService swCkSysCleaningConsTicketService;
/*
运营商：下拉框（西安地铁1、机场城际2、西安中铁（临潼线）4 failure_Operator），金额amount  张数 ticket_Number
数据类型：发售应急纸票  data_type='1'  正常情况退款 2   特殊情况退换 3
产生原因：（与数据类型关联联动） happen_Cause
（1）发售应急纸票包含内容：
因误出站发售应急纸票、 1
因误出站回收应急纸票、3
因大客流发售前往西安地铁应急纸票、2  (西安地铁去掉)
因大客流回收前往西安地铁应急纸票、4
因大客流发售前往其他运营商应急纸票、5（西安地铁去掉）
因大客流回收前往其他运营商应急纸票 6

特殊情况退票
运营故障导致（单程票、二维码电子车票、应急纸票等）退款  7

正常情况退票
非纺织城站购买（单程票、应急纸票）在西安地铁退票   8  机场线时，纺织城改为  北客站（北广场）
纺织城站购买（单程票、应急纸票）在西安地铁退票  9     机场线时，纺织城改为  北客站（北广场



清分比例根据运营商和数据类型、产生原因的具体根据上述说明的哪些值进行匹配计算？？？？？？（公式）还是只找上述金额为正数的求和？？？（参考页面最下方）
回复：误出站，按照回收金额进行清分，即各线路回收金额清分至回收线路
大客流发售应急纸票：
1、	西安地铁发售：
西安地铁回收（西安地铁总发售（来源车站配票及配备用金应急纸票发售）—14号线机场段回收—9号线回收），按照西安地铁各线路收入比例清分；
14号线机场段回收，按照西安地铁与14号线机场段收入比例清分回收金额；
9号线回收：按照西安地铁与9号线收入比例清分回收金额；
2、14号线机场段发售：
西安地铁回收按照西安地铁与14号线机场段收入比例清分回收金额；
    9号线回收，按照14号线机场段与9号线收入比例清分回收金额；
3、9号线发售：西安地铁回收按照西安地铁与9号线收入比例清分回收金额；
    14号线机场段回收，按照14号线机场段与9号线收入比例清分回收金额。

*/
    public Boolean generateSwCkClearOtherAccount(String startDate, String endDate) {
        boolean flag = false;
        //获取时间段内的西安地铁运营商和其他运营商的线路列表
        List<Map<String,String>> listLineObj = this.baseMapper.selectLineObjList(startDate,endDate);
        List<Map<String,String>> listInputPassengerWorkOtherMap = this.baseMapper.getInputPassengerWorkOtherMap(startDate,endDate);
        List<Map<String,String>> listOthenYjzpManagementMap = this.baseMapper.getOthenYjzpManagementMap(startDate,endDate);
        List<Map<String,String>> listClearRulesMap = this.baseMapper.getClearRulesMap(startDate,endDate);
        List<Map<String,String>> listClearRulesLineMap = this.baseMapper.getClearRulesLineMap(startDate,endDate);

        if (listLineObj != null && !listLineObj.isEmpty()) {
            Long sumC1 = 0L;
            Long sumC3 = 0L;

            //计算合计值
            for (Map<String,String> lineMap : listLineObj) {
                String lineCode = lineMap.get("lineCode");
				String operators = lineMap.get("operators");

                String operatorsName = lineMap.get("operatorsName");

                //各指标定义,参见word文档,下同
                Long C1 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C1 = getLong(lineCode,"6",listInputPassengerWorkOtherMap);
                } else {
                    C1 = getLong(lineCode,"6",listOthenYjzpManagementMap);
                }
                sumC1 += C1;

                Long C3 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C3 = getLong(lineCode,"5",listInputPassengerWorkOtherMap);
                } else {
                    C3 = getLong(lineCode,"5",listOthenYjzpManagementMap);
                }

                sumC3 += C3;
            }

            //插入数据库
            PigxUser user = SecurityUtils.getUser();
            List<SwCkClearOtherAccount> listSwCkClearOtherAccount = new ArrayList<>();

            for (Map<String,String> lineMap : listLineObj) {
                String lineCode = lineMap.get("lineCode");
                String operatorsName = lineMap.get("operatorsName");
                String operators = lineMap.get("operators");
				String serviceAirId ="54";

                Long A1 = 0L;////误出站应急纸票回收金额
				if(operators.equals(serviceAirId)){//城际铁路
                   A1 = getLong(lineCode,"2",listOthenYjzpManagementMap);				
				}else{//从车站录入模块获取
				   A1 = getLong(lineCode,"3",listInputPassengerWorkOtherMap); 
				
				}
				/*
                if("西安地铁".equals(operatorsName)){
                    A1 = getLong(lineCode,"3",listInputPassengerWorkOtherMap);
                } else if("城际铁路") {
                    A1 = getLong(lineCode,"3",listOthenYjzpManagementMap);
                }*/
                Long A2 = 0L;////误出站应急纸票发售金额(分)
               /*
				if("西安地铁".equals(operatorsName)){
                    A2 = getLong(lineCode,"1",listInputPassengerWorkOtherMap);
                } else {
                    A2 = getLong(lineCode,"1",listOthenYjzpManagementMap);
                }*/
				if(operators.equals(serviceAirId)){//城际铁路
                    A2 = getLong(lineCode,"1",listOthenYjzpManagementMap);		
                } else {
                    A2 = getLong(lineCode,"1",listOthenYjzpManagementMap);
                }

                Long A0 = A1 + A2;

                Long B1 = 0L;
                if("西安地铁".equals(operatorsName)){
                    B1 = getLong(lineCode,"4",listInputPassengerWorkOtherMap);
                } else {
                    B1 = getLong(lineCode,"4",listOthenYjzpManagementMap);
                }
                Long B2 = 0L;
                if("西安地铁".equals(operatorsName)){
                    B2 = getLong(lineCode,"2",listInputPassengerWorkOtherMap);
                } else {
                    B2 = getLong(lineCode,"2",listOthenYjzpManagementMap);
                }
                Double J1 = getDouble(lineCode,"agreeTicketClearProportionOther",listClearRulesLineMap);
                Long B0 = Math.round(B1 * J1);

                Long C1 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C1 = getLong(lineCode,"6",listInputPassengerWorkOtherMap);
                } else {
                    C1 = getLong(lineCode,"6",listOthenYjzpManagementMap);
                }

                Long C2 = 0L;
                if("西安地铁".equals(operatorsName)){
                    String sxtlServiceId = swCkSysCleaningConsTicketService.getSubwayServiceIdByName("陕西铁路集团");
                    C2 = Math.round(sumC1 * getDouble(sxtlServiceId,"agreeTicketClearProportionOther",listClearRulesMap)
                            * getDouble(lineCode,"faceTicketClearProportion",listClearRulesLineMap));
                } else {
                    String xadtServiceId = swCkSysCleaningConsTicketService.getSubwayServiceIdByName("西安地铁");
                    C2 = Math.round(sumC1 * getDouble(xadtServiceId,"agreeTicketClearProportionOther",listClearRulesMap));
                }

                Long C3 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C3 = getLong(lineCode,"5",listInputPassengerWorkOtherMap);
                } else {
                    C3 = getLong(lineCode,"5",listOthenYjzpManagementMap);
                }

                Long C4 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C4 = Math.round(sumC3 * getDouble(operators,"agreeTicketClearProportionOther",listClearRulesMap)
                            * getDouble(lineCode,"faceTicketClearProportion",listClearRulesLineMap));
                } else {
                    C4 = Math.round(sumC3 * getDouble(operators,"agreeTicketClearProportionOther",listClearRulesMap));
                }

                SwCkClearOtherAccount swCkClearOtherAccount = new SwCkClearOtherAccount();

                swCkClearOtherAccount.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                swCkClearOtherAccount.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                swCkClearOtherAccount.setLineCode(lineCode);

                //判断是否存在，存在改为更新，不存在插入方式
                if(this.count(Wrappers.query(swCkClearOtherAccount)) > 0){
                    continue;
                }

                swCkClearOtherAccount.setEmeTicketRecoveryAmount(A1);//误出站应急纸票回收金额(分)
                swCkClearOtherAccount.setEmeTicketSaleAmount(A2);//误出站应急纸票发售金额(分)
                swCkClearOtherAccount.setEmeTicketClearAmount(A0);//误出站应急纸票清分金额(分)

                swCkClearOtherAccount.setLpfEmeTicketRecoveryAmount(B1);//大客流应急纸票回收金额
                swCkClearOtherAccount.setLpfEmeTicketSaleAmount(B2);
                swCkClearOtherAccount.setLpfEmeTicketClearAmount(B0);

                swCkClearOtherAccount.setOtherFaultRefundAmount(C1);//非西安地铁运营商故障导致退款金额
                swCkClearOtherAccount.setOtherFaultRefundClearAmount(C2);//非西安地铁运营商故障导致退款的清分金额(分
                swCkClearOtherAccount.setSelfFaultRefundAmount(C3);//西安地铁运营商故障导致退款金额
                swCkClearOtherAccount.setSelfFaultRefundClearAmount(C4);

                swCkClearOtherAccount.setOperators(operators);

                swCkClearOtherAccount.setDeptId(user.getDeptId());
                swCkClearOtherAccount.setCreatorId(user.getId());
                swCkClearOtherAccount.setCreatorName(user.getNikeName());

                listSwCkClearOtherAccount.add(swCkClearOtherAccount);

            }

            if(!listSwCkClearOtherAccount.isEmpty()){
                this.saveBatch(listSwCkClearOtherAccount);
                flag  = true;
            }

        }
        return flag;
    }

    private Long getLong(String lineCode,String happenCause,List<Map<String,String>> listMap){
        if(listMap == null || listMap.isEmpty()){
            return 0l;
        }
        for(Map<String,String> map : listMap){
            if(lineCode.equals(map.get("lineCode")) && happenCause.equals(map.get("happenCause"))){
                return Long.parseLong(map.get("amount"));
            }
        }
        return 0l;
    }

    private Double getDouble(String condtion,String key,List<Map<String,String>> listMap){
        if(listMap == null || listMap.isEmpty()){
            return 0D;
        }
        for(Map<String,String> map : listMap){
            if(condtion.equals(map.get("condtion"))){
                return Double.parseDouble(map.get(key));
            }
        }
        return 0D;
    }
    /**
     * 重新清分
     * @param ids 清分及划账记录的ID
     * @return
     */
    public Boolean reGenerateSwCkClearOtherAccount(List<Long> ids) {
        boolean flag = false;
        PigxUser user = SecurityUtils.getUser();
        for(Long id : ids) {
            SwCkClearOtherAccount swCkClearOtherAccountDb = this.getById(id);
            String lineCode = swCkClearOtherAccountDb.getLineCode();
            String operators = swCkSysCleaningConsTicketService.getServiceOrgByLine(lineCode).get("serviceId");
            String operatorsName = swCkSysCleaningConsTicketService.getServiceOrgByLine(lineCode).get("serviceName");
            String startDate = swCkClearOtherAccountDb.getBeginTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String endDate = swCkClearOtherAccountDb.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            //获取时间段内的西安地铁运营商和其他运营商的线路列表
            List<Map<String,String>> listLineObj = this.baseMapper.selectLineObjList(startDate,endDate);
            List<Map<String,String>> listInputPassengerWorkOtherMap = this.baseMapper.getInputPassengerWorkOtherMap(startDate,endDate);
            List<Map<String,String>> listOthenYjzpManagementMap = this.baseMapper.getOthenYjzpManagementMap(startDate,endDate);
            List<Map<String,String>> listClearRulesMap = this.baseMapper.getClearRulesMap(startDate,endDate);
            List<Map<String,String>> listClearRulesLineMap = this.baseMapper.getClearRulesLineMap(startDate,endDate);

            if (listLineObj != null && !listLineObj.isEmpty()) {
                Long sumC1 = 0L;
                Long sumC3 = 0L;

                //计算合计值
                for (Map<String,String> lineMap : listLineObj) {
                    String lineCodeTmp = lineMap.get("lineCode");
                    String operatorsNameTmp = lineMap.get("operatorsName");

                    //各指标定义,参见word文档,下同
                    Long C1 = 0L;
                    if("西安地铁".equals(operatorsNameTmp)){
                        C1 = getLong(lineCodeTmp,"6",listInputPassengerWorkOtherMap);
                    } else {
                        C1 = getLong(lineCodeTmp,"6",listOthenYjzpManagementMap);
                    }
                    sumC1 += C1;

                    Long C3 = 0L;
                    if("西安地铁".equals(operatorsNameTmp)){
                        C3 = getLong(lineCodeTmp,"5",listInputPassengerWorkOtherMap);
                    } else {
                        C3 = getLong(lineCodeTmp,"5",listOthenYjzpManagementMap);
                    }

                    sumC3 += C3;
                }

                //更新数据库

                Long A1 = 0L;
                if("西安地铁".equals(operatorsName)){
                    A1 = getLong(lineCode,"3",listInputPassengerWorkOtherMap);
                } else {
                    A1 = getLong(lineCode,"3",listOthenYjzpManagementMap);
                }
                Long A2 = 0L;
                if("西安地铁".equals(operatorsName)){
                    A2 = getLong(lineCode,"1",listInputPassengerWorkOtherMap);
                } else {
                    A2 = getLong(lineCode,"1",listOthenYjzpManagementMap);
                }
                Long A0 = A1 + A2;

                Long B1 = 0L;
                if("西安地铁".equals(operatorsName)){
                    B1 = getLong(lineCode,"4",listInputPassengerWorkOtherMap);
                } else {
                    B1 = getLong(lineCode,"4",listOthenYjzpManagementMap);
                }
                Long B2 = 0L;
                if("西安地铁".equals(operatorsName)){
                    B2 = getLong(lineCode,"2",listInputPassengerWorkOtherMap);
                } else {
                    B2 = getLong(lineCode,"2",listOthenYjzpManagementMap);
                }
                Double J1 = getDouble(lineCode,"agreeTicketClearProportionOther",listClearRulesLineMap);
                Long B0 = Math.round(B1 * J1);

                Long C1 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C1 = getLong(lineCode,"6",listInputPassengerWorkOtherMap);
                } else {
                    C1 = getLong(lineCode,"6",listOthenYjzpManagementMap);
                }

                Long C2 = 0L;
                if("西安地铁".equals(operatorsName)){
                    String sxtlServiceId = swCkSysCleaningConsTicketService.getSubwayServiceIdByName("陕西铁路集团");
                    C2 = Math.round(sumC1 * getDouble(sxtlServiceId,"agreeTicketClearProportionOther",listClearRulesMap)
                            * getDouble(lineCode,"faceTicketClearProportion",listClearRulesLineMap));
                } else {
                    String xadtServiceId = swCkSysCleaningConsTicketService.getSubwayServiceIdByName("西安地铁");
                    C2 = Math.round(sumC1 * getDouble(xadtServiceId,"agreeTicketClearProportionOther",listClearRulesMap));
                }

                Long C3 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C3 = getLong(lineCode,"5",listInputPassengerWorkOtherMap);
                } else {
                    C3 = getLong(lineCode,"5",listOthenYjzpManagementMap);
                }

                Long C4 = 0L;
                if("西安地铁".equals(operatorsName)){
                    C4 = Math.round(sumC3 * getDouble(operators,"agreeTicketClearProportionOther",listClearRulesMap)
                            * getDouble(lineCode,"faceTicketClearProportion",listClearRulesLineMap));
                } else {
                    C4 = Math.round(sumC3 * getDouble(operators,"agreeTicketClearProportionOther",listClearRulesMap));
                }

                SwCkClearOtherAccount swCkClearOtherAccount = new SwCkClearOtherAccount();

                swCkClearOtherAccount.setBeginTime(LocalDate.parse(startDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                swCkClearOtherAccount.setEndTime(LocalDate.parse(endDate,  DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                swCkClearOtherAccount.setLineCode(lineCode);

                swCkClearOtherAccount.setEmeTicketRecoveryAmount(A1);
                swCkClearOtherAccount.setEmeTicketSaleAmount(A2);
                swCkClearOtherAccount.setEmeTicketClearAmount(A0);

                swCkClearOtherAccount.setLpfEmeTicketRecoveryAmount(B1);
                swCkClearOtherAccount.setLpfEmeTicketSaleAmount(B2);
                swCkClearOtherAccount.setLpfEmeTicketClearAmount(B0);

                swCkClearOtherAccount.setOtherFaultRefundAmount(C1);
                swCkClearOtherAccount.setOtherFaultRefundClearAmount(C2);
                swCkClearOtherAccount.setSelfFaultRefundAmount(C3);
                swCkClearOtherAccount.setSelfFaultRefundClearAmount(C4);

                swCkClearOtherAccount.setOperators(operators);

                swCkClearOtherAccount.setDeptId(user.getDeptId());
                swCkClearOtherAccount.setCreatorId(user.getId());
                swCkClearOtherAccount.setCreatorName(user.getNikeName());

                MyBeanUtils.copyProperties(swCkClearOtherAccount,swCkClearOtherAccountDb);
                swCkClearOtherAccountDb.setUpdateTime(LocalDateTime.now());
                this.updateById(swCkClearOtherAccountDb);

                /////////////////更新数据库 end/////////////
                flag  = true;
            }
        }

        return flag;
    }
}
